/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/parser/deserializer/RectangleDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: RectangleDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.parser.deserializer;

import java.awt.Rectangle;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Set;

import com.elancom.framework.commons.json.JSONException;
import com.elancom.framework.commons.json.parser.DefaultJSONParser;
import com.elancom.framework.commons.json.parser.JSONScanner;
import com.elancom.framework.commons.json.parser.JSONToken;

public class RectangleDeserializer implements AutowiredObjectDeserializer {

	public final static RectangleDeserializer instance = new RectangleDeserializer();

	@Override
	@SuppressWarnings("unchecked")
	public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
		final JSONScanner lexer = (JSONScanner) parser.getLexer();

		if (lexer.token() == JSONToken.NULL) {
			lexer.nextToken();
			return null;
		}

		if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) {
			throw new JSONException("syntax error");
		}
		lexer.nextToken();

		int x = 0, y = 0, width = 0, height = 0;
		for (;;) {
			if (lexer.token() == JSONToken.RBRACE) {
				lexer.nextToken();
				break;
			}

			String key;
			if (lexer.token() == JSONToken.LITERAL_STRING) {
				key = lexer.stringVal();
				lexer.nextTokenWithColon(JSONToken.LITERAL_INT);
			} else {
				throw new JSONException("syntax error");
			}

			int val;
			if (lexer.token() == JSONToken.LITERAL_INT) {
				val = lexer.intValue();
				lexer.nextToken();
			} else {
				throw new JSONException("syntax error");
			}

			if (key.equalsIgnoreCase("x")) {
				x = val;
			} else if (key.equalsIgnoreCase("y")) {
				y = val;
			} else if (key.equalsIgnoreCase("width")) {
				width = val;
			} else if (key.equalsIgnoreCase("height")) {
				height = val;
			} else {
				throw new JSONException("syntax error, " + key);
			}

			if (lexer.token() == JSONToken.COMMA) {
				lexer.nextToken(JSONToken.LITERAL_STRING);
			}
		}

		return (T) new Rectangle(x, y, width, height);
	}

	@Override
	public int getFastMatchToken() {
		return JSONToken.LBRACE;
	}

	@Override
	public Set<Type> getAutowiredFor() {
		return Collections.<Type> singleton(Rectangle.class);
	}
}
